package utility;

import java.security.*;
import java.io.*;
import java.util.*;

public class Hash {

    static final String HEXES = "0123456789ABCDEF";

    public static String calcolaHash(File file) throws Exception {

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        MessageDigest md = MessageDigest.getInstance("MD5");
        DigestInputStream digestIn = new DigestInputStream(bis, md);
        while (digestIn.read() != -1);
        byte[] digest = md.digest();
        final StringBuilder hex = new StringBuilder(2 * digest.length);
        for (final byte b : digest) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();

    }

    /*
     * public static void verificaHash(String fileIn, String fileHash) throws
     * Exception {
     *
     * byte[] digest = calcolaHash(fileIn); FileInputStream fis = new
     * FileInputStream(fileHash); ByteArrayOutputStream baos = new
     * ByteArrayOutputStream(); int b = 0; while ((b = fis.read()) != -1) {
     * baos.write(b); } byte[] hashSaved = baos.toByteArray(); if
     * (Arrays.equals(digest, hashSaved)) { System.out.println("L'impronta
     * combacia"); } else { System.out.println("L'impronta non combacia");
     *
     * }
     *
     * }
     *
     * public static void main(String args[]) throws Exception { if (args.length
     * < 2 || (args[0].equals("-v") && args.length != 3)) {
     * System.out.println("Usage: Hash -c || -v fileInput [se -v]
     * fileImpronta\n" + "opzioni: -c calcola l'hash e lo salva in fileOutput\n"
     * + "opzioni: -v verifica l'hash di fileOutput con fileImpronta\n" + "ad
     * esempio: Hash -c file.txt\n" + " Hash -v file.txt hashFile.txt\n");
     * System.exit(1); }
     *
     * if (args[0].equals("-c")) { FileOutputStream fos = new
     * FileOutputStream("hash" + args[1]); fos.write(calcolaHash(args[1]));
     * fos.close(); } else if (args[0].equals("-v")) { verificaHash(args[1],
     * args[2]); }
     *
     * }
     */
}